package com.flyxiaozhu.erp.core.repositories;

import com.flyxiaozhu.erp.core.entities.GoodsSku;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.persistence.LockModeType;
import javax.transaction.Transactional;
import java.util.Collection;
import java.util.List;

/**
 * @author flyxiaozhu
 * @date 2019-04-17 23:16
 */
public interface GoodsSkuRepository extends JpaRepository<GoodsSku, Long> {
    //    @Query(value = "SELECT * FROM goods_sku sku WHERE sku.goods_id = ?1 AND sku.id NOT IN ?2", nativeQuery = true)
    List<GoodsSku> findByGoodsIdAndIdNotIn(long goodsId, Collection<Long> ids);

    // 排他琐，属于悲观琐，原生sql不能使用@Lock，进行加琐
    @Query(value = "SELECT * FROM goods_sku sku WHERE sku.goods_id = ?1 FOR UPDATE ", nativeQuery = true)
    List<GoodsSku> findByGoodsIdOnLock(long goodsId);

    List<GoodsSku> findByGoodsId(long goodsId);

    void deleteAllByGoodsIdIn(Collection goodsIds);

    @Query("select s.id, s.stock from GoodsSku s where s.goodsId = ?1")
    List<Object> getStockByGoodsId(long goodsId);

    List<GoodsSku> findByIdIn(Collection ids);

    @Query("update GoodsSku g set g.stock = g.stock - ?2 where g.id = ?1")
    @Modifying
    @Transactional
    void decStock(long id, int num);

    @Query("update GoodsSku g set g.stock = g.stock + ?2 where g.id = ?1")
    @Modifying
    @Transactional
    void incStock(long id, int num);

    @Query("select s from GoodsSku s where s.id = ?1")
    @Lock(LockModeType.WRITE) // 乐观琐
    GoodsSku findByIdOnLock(long id);
}
